<template>
  <el-dialog
    title="接班信息"
    :visible.sync="dialogVisible"
    :modal="true"
    :appendToBody="true"
    :width="device == 'desktop' ? '70%' : '90%'"
    v-dialog-drag
    :close-on-click-modal="false"
    :destroy-on-close="true"
    top="5vh"
    @close="handleClose()"
    @open="handleOpen()"
  >
    <div class="dialog-body-content" :key="updateKey" v-loading="loading">
      <el-collapse
        :value="[
          '1',
          '2',
          'members',
          'task',
          'rawMaterial',
          'equipOperationStatus',
          'taskProcessingStatus',
          'abnormalHandlingStatus',
          'stationLog',
        ]"
      >
        <el-collapse-item name="1">
          <template slot="title">
            <PartitionTitle title="接班详情"></PartitionTitle>
          </template>
          <el-form
            ref="BaseForm"
            :model="baseForm"
            label-width="140px"
            size="small"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="所属车间" prop="workshopId">
                  <el-select
                    v-model="baseForm.workshopId"
                    placeholder="请选择所属车间"
                    @change="handleWorkshopChange"
                  >
                    <el-option
                      v-for="item in workshopOptions"
                      :key="item.workshopId"
                      :label="item.workshopName"
                      :value="item.workshopId"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="产线" prop="lineId">
                  <el-select
                    v-model="baseForm.lineId"
                    placeholder="请选择所属产线"
                    @change="handleLineIdChange"
                  >
                    <el-option
                      v-for="item in lineOptions"
                      :key="item.lineId"
                      :label="item.lineName"
                      :value="item.lineId"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="班组" prop="groupId">
                  <el-select
                    v-model="baseForm.groupId"
                    placeholder="请选择所属班组"
                  >
                    <el-option
                      v-for="item in groupOptions"
                      :key="item.id"
                      :label="item.erpWorkGroupDesc"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="实际工作开始时间" prop="workStartTime">
                  <el-date-picker
                    v-model="baseForm.workStartTime"
                    type="datetime"
                    placeholder="选择日期时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="是否头班">
                  <el-input
                    type="text"
                    :value="group ? '否' : '是'"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <!-- 生产任务单，车间类型为水处理车间、调配车间、生产公共的，接班时不需要产生工单信息 -->
          <Task
            v-if="
              takeoverDetailsData &&
              !['WATER', 'ALLOCATE', 'PRODUCTION_PUBLIC'].includes(
                takeoverDetailsData.workshopType
              )
            "
            status="1"
            detailKey="takeoverDetail"
          ></Task>
          <Members status="1" detailKey="takeoverDetail"></Members>
        </el-collapse-item>
        <el-collapse-item
          name="2"
          v-if="group && ['HANDOVERED', 'PREPARE'].includes(group.status)"
        >
          <template slot="title">
            <PartitionTitle title="交班详情"></PartitionTitle>
          </template>
          <el-form :model="baseForm1" label-width="150px" size="small">
            <el-row>
              <el-col :span="8">
                <el-form-item label="产线" prop="lineName">
                  <el-input
                    type="text"
                    v-model="baseForm1.lineName"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="班组" prop="groupName">
                  <el-input
                    type="text"
                    v-model="baseForm1.groupName"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="实际工作开始时间"
                  prop="workStartTime"
                  label-width="150px"
                >
                  <el-input
                    type="text"
                    v-model="baseForm1.workStartTime"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item
                  label="下一班是否连续生产"
                  prop="continuousProduce"
                  label-width="150px"
                >
                  <div class="box">
                    <el-select
                      v-model="baseForm1.continuousProduce"
                      placeholder="请选择"
                      class="w1"
                      disabled
                    >
                      <el-option label="是" value="Y"> </el-option>
                      <el-option label="否" value="N"> </el-option>
                    </el-select>
                    <el-select
                      v-if="baseForm1.continuousProduce === 'N'"
                      v-model="baseForm1.notContinuousReason"
                      placeholder="请选择"
                      disabled
                    >
                      <el-option label="换型" value="换型"> </el-option>
                      <el-option label="停机" value="停机"> </el-option>
                    </el-select>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="计划停机时长(小时)"
                  prop="planDowntimeDur"
                  label-width="150px"
                >
                  <el-input
                    type="text"
                    v-model="baseForm1.planDowntimeDur"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="实际工作结束时间"
                  prop="workEndTime"
                  label-width="150px"
                >
                  <el-input
                    type="text"
                    v-model="baseForm1.workEndTime"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <Members status="3" detailKey="handoverDetail"></Members>
          <!-- 原材料信息 -->
          <RawMaterial
            v-if="
              handoverDetailsData &&
              !['WATER', 'ALLOCATE', 'PRODUCTION_PUBLIC'].includes(
                handoverDetailsData.workshopType
              )
            "
            status="3"
          ></RawMaterial>
          <!-- 设备运行情况 -->
          <EquipOperationStatus></EquipOperationStatus>
          <!-- 任务处理情况 -->
          <TaskProcessingStatus status="3"></TaskProcessingStatus>
          <!-- 异常处理情况 -->
          <AbnormalHandlingStatus status="3"></AbnormalHandlingStatus>
          <!-- 工位交接日志 -->
          <StationLog status="3"></StationLog>
        </el-collapse-item>
      </el-collapse>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button
        type="default"
        :loading="saveloading"
        @click="dialogVisible = false"
        >取消</el-button
      >
      <el-button
        v-if="buttons.includes('start')"
        type="primary"
        :loading="saveloading"
        @click="handleStart"
        >开始生产</el-button
      >
      <el-button
        v-if="buttons.includes('prepare')"
        type="primary"
        :loading="saveloading"
        @click="handlePrepare"
        >生产准备</el-button
      >
      <el-button
        v-if="buttons.includes('submit')"
        type="primary"
        :loading="saveloading"
        @click="handleSubmit"
        >确认接班</el-button
      >
      <el-button
        v-if="buttons.includes('confirm')"
        type="primary"
        :loading="saveloading"
        @click="handleConfirm"
        >确认生产</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import Task from "../components/task";
import Members from "../components/members";
import RawMaterial from "../components/rawMaterial";
import EquipOperationStatus from "../components/equipOperationStatus";
import TaskProcessingStatus from "../components/taskProcessingStatus";
import AbnormalHandlingStatus from "../components/abnormalHandlingStatus";
import StationLog from "../components/stationLog";
import { mapMutations, mapState, mapGetters } from "vuex";
import {
  getUserChargedLineAndGroup,
  getProduceDetails,
  getTakeoverInfoById,
  submitProduce,
  prepareProduce,
} from "@/api/shifts/turnOnDuty";
import { getErpGroupsByLineId } from "@/api/team/group";
import WorkTree from "@/utils/workTree";
export default {
  components: {
    Task,
    Members,
    RawMaterial,
    EquipOperationStatus,
    TaskProcessingStatus,
    AbnormalHandlingStatus,
    StationLog,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    // 被接替的班组，有值，表示连续生产，为null，表示非连续生产
    group: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      updateKey: 1,
      loading: false,
      saveloading: false,
      workTree: null,
      buttonsMap: {
        // 非连续生产显示按钮(<开始生产>)
        disContinuous: ["start"],
        // 连续生产，上一个班组是“生产中”(<生产准备>)
        continuous1: ["prepare"],
        // 连续生产，上一个班组是“已交班”(<确认接班>)
        continuous2: ["submit"],
        // 连续生产，本班组是“生产准备”(<确认生产>)
        continuous3: ["confirm"],
      },
      // 接班详情
      baseForm: {
        factoryDeptId: null,
        factoryDeptCode: null,
        workshopId: null,
        lineName: null,
        lineId: null,
        groupName: null,
        groupId: null,
        workStartTime: null,
      },
      workshopOptions: [], //车间列表
      lineOptions: [], //产线列表
      groupOptions: [], // 班组列表
      // 交班详情
      baseForm1: {
        lineName: null,
        lineId: null,
        groupName: null,
        groupId: null,
        workStartTime: null,
        continuousProduce: null,
        notContinuousReason: null,
        planDowntimeDur: null,
        workEndTime: null,
      },
    };
  },
  computed: {
    ...mapGetters(["device"]),
    ...mapState({
      takeoverDetailsData: (state) => state.turnOnDuty.takeoverDetail,
      handoverDetailsData: (state) => state.turnOnDuty.handoverDetail,
    }),
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
    buttons() {
      // 但无法查询到详情数据，不能做操作
      if (!this.takeoverDetailsData) {
        return [];
      }

      // 是否连续生产
      const isContinuous = !!this.group;
      // 非连续生产
      if (!isContinuous) {
        return this.buttonsMap.disContinuous;
      }
      const status = this.group?.status || null;
      // 生产中
      if (status === "PRODUCING") {
        return this.buttonsMap.continuous1;
      }
      // 已交班
      if (status === "HANDOVERED") {
        return this.buttonsMap.continuous2;
      }
      // 生产准备
      if (status === "PREPARE") {
        return this.buttonsMap.continuous3;
      }
    },
    canGetTakeOverDetail() {
      const { workshopId, lineId, groupId } = this.baseForm;
      return `${workshopId}-${lineId}-${groupId}`;
    },
  },
  methods: {
    ...mapMutations("turnOnDuty", ["SET_TAKEOVERDETAIL", "SET_HANDOVERDETAIL"]),
    handleClose() {
      this.SET_TAKEOVERDETAIL(null);
      this.SET_HANDOVERDETAIL(null);
      this.baseForm = {
        factoryDeptId: null,
        factoryDeptCode: null,
        workshopId: null,
        lineName: null,
        lineId: null,
        groupName: null,
        groupId: null,
        workStartTime: null,
      };
      this.$refs.BaseForm.resetFields();
    },
    handleOpen() {
      this.workTree = new WorkTree();

      this.workTree
        .affterLoad()
        .then(() => {
          // 获取当前登陆人负责的产线/班组
          this.getUserChargedLineAndGroup();
        })
        .catch(() => {});

      if (this.group?.status == "PREPARE") {
        // 生产准备，实际工作开始实际取以保存的
        this.baseForm.workStartTime = this.group.workStartTime;
      } else {
        // 每次打开，实际工作开始时间默认显示当前时间
        this.baseForm.workStartTime = this.parseTime(
          new Date(),
          "{y}-{m}-{d} {h}:{i}:{s}"
        );
      }
    },
    // 获取用户负责的产线班组
    getUserChargedLineAndGroup() {
      this.loading = true;
      getUserChargedLineAndGroup()
        .then(async (res) => {
          if (res.data?.userChargedLines?.length) {
            const userChargedLines = res.data.userChargedLines;

            // 工厂
            this.baseForm.factoryDeptId =
              userChargedLines[0].factoryDeptId || null;
            this.baseForm.factoryDeptCode =
              userChargedLines[0].factoryDeptCode || null;

            // 已经接了某个车间/产线的，默认还是显示已接的车间/产线，否则默认显示负责的产线
            if (!this.group?.lineId) {
              // 车间默认选中：产线负责人所在的车间(多个时，默认第一个)
              this.baseForm.workshopId =
                userChargedLines[0].workshopDto?.id || null;

              // 产线默认选中：产线负责人(多个时，默认第一个)
              this.baseForm.lineId = userChargedLines[0].id || null;
              this.baseForm.lineName =
                userChargedLines[0].erpProductionLineName || null;
            } else {
              this.baseForm.workshopId = this.group.workshopId;
              this.baseForm.lineId = this.group.lineId;
              this.baseForm.lineName = this.group.lineName;
            }

            // 车间选项，当前登录人所负责的产线(产线负责人)所在的车间
            const ids = userChargedLines.map((ele) => ele.id);
            this.workshopOptions = this.workTree
              .getProductionLine((ele) => {
                return ids.includes(ele.lineId);
              })
              .map((ele) => ({
                ...ele,
                workshopName: ele.parent.workshopName,
              }));

            // 产线选项，当前登录人所负责的产线(产线负责人)所在的车间下所有产线
            this.lineOptions = this.workTree.getProductionLine({
              workshopId: this.baseForm.workshopId,
            });

            // 班组选项，所选产线下的班组
            await this.handleLineIdChange(this.baseForm.lineId);

            // 已经接了某个班的，默认还是显示已接班组，否则默认显示班组负责人
            if (!this.group?.groupId) {
              // 班组默认值，若所选产线下的班组不包含接口返回的登陆人所属班组负责人的班组，则不显示班组默认选中值
              const userChargedGroups = res.data?.userChargedGroups || [];
              const groupIds = userChargedGroups.map((ele) => ele.id);
              const existGroup = this.groupOptions.find((ele) =>
                groupIds.includes(ele.id)
              );
              this.baseForm.groupId = existGroup?.id || null;
              this.baseForm.groupName = existGroup?.erpWorkGroupDesc || null;
            } else {
              this.baseForm.groupId = this.group.groupId;
              this.baseForm.groupName = this.group.groupName;
            }
          }

          this.loading = false;
        })
        .catch(() => {
          this.baseForm.factoryDeptId = null;
          this.baseForm.factoryDeptCode = null;
          this.baseForm.workshopId = null;
          this.baseForm.lineId = null;
          this.baseForm.lineName = null;
          this.baseForm.groupId = null;
          this.baseForm.groupName = null;
          this.loading = false;
        });
    },
    // 查询接班详情
    getTakeOverDetails() {
      const { workshopId, lineId, groupId } = this.baseForm;
      // 判断是否车间，产线，班组都有已选值，只要有一个没有选择，则不进行详情查询，无法接班
      if (!workshopId || !lineId || !groupId) {
        this.SET_TAKEOVERDETAIL(null);
        this.SET_HANDOVERDETAIL(null);
        this.updateKey++;
        return;
      }
      this.loading = true;
      let param = {
        preProduceLogId: this.group?.id || null,
        workshopId: workshopId,
        lineId: lineId,
        groupId: groupId,
      };

      // 生产准备状态的班，调用getTakeoverInfoById接口，获取当前生产准备的接班详情
      let getDetailFn = getProduceDetails;
      if (this.group?.status == "PREPARE") {
        param = this.group?.id;
        getDetailFn = getTakeoverInfoById;
      }

      getDetailFn(param)
        .then((res) => {
          this.SET_TAKEOVERDETAIL(res?.data || null);

          // 已经交班的，显示已交班信息
          const { preTakeAndHandVo } = res.data;
          if (preTakeAndHandVo) {
            this.SET_HANDOVERDETAIL(preTakeAndHandVo || null);
            this.baseForm1 = {
              lineName: preTakeAndHandVo.lineName,
              groupName: preTakeAndHandVo.groupName,
              workStartTime: preTakeAndHandVo.workStartTime,
              continuousProduce: preTakeAndHandVo.continuousProduce,
              notContinuousReason: preTakeAndHandVo.notContinuousReason,
              planDowntimeDur: preTakeAndHandVo.planDowntimeDur,
              workEndTime: preTakeAndHandVo.workEndTime,
            };
          }
          this.updateKey++;
          this.loading = false;
        })
        .catch(() => {
          this.SET_TAKEOVERDETAIL(null);
          this.SET_HANDOVERDETAIL(null);
          this.updateKey++;
          this.loading = false;
        });
    },
    // 改变车间，更新该车间下的产线列表
    handleWorkshopChange(value) {
      this.lineOptions = this.workTree.getProductionLine({
        workshopId: value,
      });
      // 清空产线选中项
      this.baseForm.lineId = null;
      this.baseForm.lineName = null;
    },
    // 改变产线，更新该产线下的班组
    async handleLineIdChange(value) {
      if (!value) {
        return;
      }
      try {
        const res = await getErpGroupsByLineId(value);
        this.groupOptions = res || [];
      } catch (error) {
        this.groupOptions = [];
        console.error(error);
      }
      // 清空班组选中项
      this.baseForm.groupId = null;
      this.baseForm.groupName = null;
    },
    // 参数
    getSaveParams() {
      if (!this.takeoverDetailsData) {
        return null;
      }
      const param = {
        produceLogId: this.takeoverDetailsData.produceLogId,
        factoryDeptCode: this.takeoverDetailsData.factoryDeptCode,
        preProduceLogId: this.takeoverDetailsData.preProduceLogId,
        workshopId: this.baseForm.workshopId,
        lineId: this.takeoverDetailsData.lineId,
        groupId: this.takeoverDetailsData.groupId,
        produceDate: this.takeoverDetailsData.produceDate,
        workStartTime: this.baseForm.workStartTime,
        orderDtos:
          this.takeoverDetailsData.orderDtos?.map((ele) => ({
            id: ele.id,
            orderSn: ele.orderSn,
            itemCode: ele.itemCode,
          })) || [],
        workStationUserVos:
          this.takeoverDetailsData.workStationUserVos?.map((ele) => ({
            workStationId: ele.workStationId,
            workType: ele.workType,
            workStationUserHourVos: ele.workStationUserHourVos.map((user) => ({
              username: user.username,
            })),
          })) || [],
        workshopType: this.takeoverDetailsData.workshopType,
      };

      // 校验
      // 车间类型为水处理车间、调配车间、生产公共的，接班时不需要产生工单信息
      if (
        !["WATER", "ALLOCATE", "PRODUCTION_PUBLIC"].includes(
          param.workshopType
        ) &&
        !param.orderDtos?.length
      ) {
        this.msgWarning("未确认生产工单，不可接班");
        return false;
      }
      // 每个工位必须配人
      const emtyUser = param.workStationUserVos.find(
        (ele) => !ele.workStationUserHourVos?.length
      );
      if (emtyUser) {
        this.msgWarning("每个工位必须分配人员");
        return false;
      }

      return param;
    },
    // 开始生产
    handleStart() {
      this.$confirm("是否确定开始工作？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const param = this.getSaveParams();
          if (!param) {
            return;
          }
          this.saveloading = true;
          submitProduce(param)
            .then((res) => {
              this.msgSuccess("操作成功！");
              this.$emit("refresh");
              this.dialogVisible = false;
              this.saveloading = false;
              // 刷新基础权限数据
              this.$store.dispatch("getAllData");
              this.$store.dispatch("getWorkUserInfo");
            })
            .catch(() => {
              this.saveloading = false;
            });
        })
        .catch(() => {});
    },
    // 生产准备
    handlePrepare() {
      this.$confirm("是否确定开始工作？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const param = this.getSaveParams();
          if (!param) {
            return;
          }
          this.saveloading = true;
          prepareProduce(param)
            .then((res) => {
              this.msgSuccess("接班准备成功！");
              this.$emit("refresh");
              this.dialogVisible = false;
              this.saveloading = false;
              // 刷新基础权限数据
              this.$store.dispatch("getAllData");
              this.$store.dispatch("getWorkUserInfo");
            })
            .catch(() => {
              this.saveloading = false;
            });
        })
        .catch(() => {});
    },
    // 确认接班
    handleSubmit() {
      this.$confirm("是否确定接班？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const param = this.getSaveParams();
          if (!param) {
            return;
          }
          this.saveloading = true;
          submitProduce(param)
            .then((res) => {
              this.msgSuccess("接班成功！");
              this.$emit("refresh");
              this.dialogVisible = false;
              this.saveloading = false;
              // 刷新基础权限数据
              this.$store.dispatch("getAllData");
              this.$store.dispatch("getWorkUserInfo");
            })
            .catch(() => {
              this.saveloading = false;
            });
        })
        .catch(() => {});
    },
    // 确认生产
    handleConfirm() {
      this.$confirm("是否确定生产？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const param = this.getSaveParams();
          if (!param) {
            return;
          }
          this.saveloading = true;
          submitProduce(param)
            .then((res) => {
              this.msgSuccess("接班成功！");
              this.$emit("refresh");
              this.dialogVisible = false;
              this.saveloading = false;
              // 刷新基础权限数据
              this.$store.dispatch("getAllData");
              this.$store.dispatch("getWorkUserInfo");
            })
            .catch(() => {
              this.saveloading = false;
            });
        })
        .catch(() => {});
    },
  },
  watch: {
    canGetTakeOverDetail: {
      handler() {
        this.getTakeOverDetails();
      },
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-collapse {
  border: none;
  .el-collapse-item__wrap {
    border: none;
  }
}
.block-title {
  margin-bottom: 0;
}
.box {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}
.el-form {
  .el-select,
  .el-date-editor.el-input {
    width: 100%;
  }
}
</style>
